package org.company.mars.activemq;

import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicSubscriber;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

public class TopicReceiver implements MessageListener{
	
	private Session session = null;
	private Connection connection = null;
	
	private static Integer count = 0;
	
	public void subscribe() throws JMSException {
		ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_BROKER_URL);
		connection = factory.createConnection();
		connection.setClientID("hucw" + (count++));
		connection.start();
		boolean transacted = false;
		session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);
		Topic topic = session.createTopic("topic.message");
		//Destination control = session.createTopic("topic.control");
		//MessageConsumer consumer = session.createConsumer(topic);
		TopicSubscriber receiver = session.createDurableSubscriber(topic, "hucw" + count);
		receiver.setMessageListener(this);
		
		/*producer = session.createProducer(topic);
		System.out.println("Waiting for messages...");*/
	}
	
	public void onMessage(Message message) {
		// TODO Auto-generated method stub
		TextMessage txtMessage = (TextMessage)message;
		String text = null;
		try {
			text = txtMessage.getText();
			System.out.println("receive is 【" + text + "】");
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
